"""
项目初始化涉及方法
"""
from flask import request, g
from components.memcache.connector import cache
from components.nacos.service import register_service, send_heartbeat_thread, get_service_url
from utils.views import resp_with_data


def register_middleware(app):
    @app.before_request
    def request_to_g():
        path_list = request.path.split('/')
        # 版本 支持灰度发布，支持header传参，支持显示url传参，优先级：header > url > 默认
        version = request.args.get('version') if request.args.get('version') else 'v1.0'
        version = request.headers.get('version') if request.headers.get('version') else version
        # print(version)
        # 服务未找到
        service_url = get_service_url(path_list[1], version)
        if not service_url:
            return resp_with_data(10016)
        g.service_url = service_url
        # 鉴权
        authorization = request.headers.get('Authorization')
        # 如果 Authorization 头不存在，authorization_header 将会是 None
        if authorization:
            token = authorization
            if not token:
                return resp_with_data(10006)
            if not cache.get(token.encode('utf-8')):
                return resp_with_data(10007)
        else:
            if path_list[2] not in ['static', 'common', 'public']:
                return resp_with_data(10011)


# 发送到Nacos服务注册接口
def register_heartbeat_to_nacos():
    register_service()
    send_heartbeat_thread()
